import { Controller } from 'egg';
import * as _ from 'lodash';

export default class CustomerController extends Controller {
  /**
   * 迁移客户的索引
   */
  public async rebuildCustomerIndex() {
    const { ctx } = this;
    ctx.logger.info('--------begin rebuild customer index------');
    try {
      const data = ctx.request.body.data;
      await ctx.service.customer.customer.rebuildIndex(data);
      ctx.setSuccess();
    } catch (err) {
      ctx.logger.error(err);
    }
    ctx.logger.info('--------over rebuild customer index------');
    ctx.sendResult();
  }

  /**
   * 修改账户,改回solr
   */
  public async recoveryCustomerIndex() {
    const { ctx, app } = this;
    try {
      // 查询要处理的账户
      const data = ctx.request.body.data;
      // 定义查询条件
      let query = {};
      if (data && data.account) {
        if (typeof (data.account) === 'string') {
          query = {_id: data.account};
        }
        if (typeof (data.account) === 'object') {
          const ids = _.uniq(data.account);
          query = {_id: {$in: ids}};
        }
      }
      ctx.logger.info('--------recoveryCustomerIndex------ ' + JSON.stringify(query));
      await app.commonDB.db(app.constants.BILL).collection(app.constants.DB_PLATFORM_ACCOUNT_PRODUCT)
        .updateMany(query, {$unset: {readEs: 1}});
      ctx.setSuccess();
    } catch (err) {
      ctx.logger.info('--------recoveryCustomerIndex------ ' + err.message);
      ctx.logger.error(err);
    }
    ctx.sendResult();
  }

  /**
   * 修改账户,变成es
   */
  public async changeCustomerIndex() {
    const { ctx, app } = this;
    try {
      // 查询要处理的账户
      const data = ctx.request.body.data;
      // 定义查询条件
      let query = {};
      if (data && data.account) {
        if (typeof (data.account) === 'string') {
          query = {_id: data.account + '_cc'};
        }
        if (typeof (data.account) === 'object') {
          let ids: any = [];
          for (const id of data.account) {
            ids.push(id + '_cc');
          }
          ids = _.uniq(ids);
          query = {_id: {$in: ids}};
        }
      }
      await app.commonDB.db(app.constants.BILL).collection(app.constants.DB_PLATFORM_ACCOUNT_PRODUCT)
        .updateMany(query, {$set: {readEs: true}});
      ctx.setSuccess();
    } catch (err) {
      ctx.logger.info('--------changeCustomerIndex------' + err.message);
      ctx.logger.error(err);
    }
    ctx.sendResult();
  }

  /**
   * 获取迁移成功的账户的数量
   */
  public async getRebuildAccount() {
    const { ctx, app } = this;
    try {
      const returnFields = {
        account: 1,
        dataDB: 1,
        readEs: 1,
      };
      const accountDocs: any[] = [];
      const accountCursor = await app.commonDB.db(app.constants.BILL).collection(app.constants.DB_PLATFORM_ACCOUNT_PRODUCT)
        .find({}, {projection: returnFields});
      while (await accountCursor.hasNext()) {
        const accountTemp = await accountCursor.next();
        accountDocs.push(accountTemp);
      }
      let totalCount: number = 0;
      let successCount: number = 0;
      const array: any = [];
      for (const account of accountDocs) {
        if (account.dataDB) {
          totalCount++;
        }
        if (account.readEs) {
          array.push(account._id);
          successCount++;
        }
      }
      ctx.logger.info('--------getRebuildAccount--********总数*****--count--' + totalCount);
      ctx.logger.info('--------getRebuildAccount--********迁移数*****--count--' + successCount);
      // ctx.logger.info('--------getRebuildAccount--********迁移account*****-----' + JSON.stringify(array));
      ctx.setSuccess();
    } catch (err) {
      ctx.logger.error(err);
    }
    ctx.sendResult();
  }

  /**
   * 获取账户数据
   */
  public async getAccount() {
    const { ctx, app } = this;
    try {
      // 定义返回字段
      const returnFields = {
        account: 1,
        dataDB: 1,
        readEs: 1,
      };
      // 'N00000007003'
      const accountId: string = 'N00000007003';
      // const accountId: string = 'N00000002412';
      const accountInfo = await app.commonDB.db(app.constants.BILL).collection(app.constants.DB_PLATFORM_ACCOUNT_PRODUCT)
        .findOne({_id: accountId + '_cc'}, {projection: returnFields});
      const customer1 = await app.commonDB.db(accountInfo.dataDB).collection(accountId + app.constants.DB_CUSTOMER)
        .findOne({}, {sort: {createTime: 1}, projection: {createTime: 1}});
      const customer2 = await app.commonDB.db(accountInfo.dataDB).collection(accountId + app.constants.DB_CUSTOMER)
        .findOne({}, {sort: {createTime: -1}, projection: {createTime: 1}});
      // 2016-10-25 13:32:51   2018-07-14 18:08:51
      // const customerArray: any[] = [];
      // const customerCursor = await app.commonDB.db(accountInfo.dataDB).collection(accountId + app.constants.DB_CUSTOMER)
      //   .find({createTime: { $gte: '2016-10-25 00:00:00', $lt: '2017-04-14 00:00:00'}}, {projection: {_id: 1}});
      // while (await customerCursor.hasNext()) {
      //   const customerTemp = await customerCursor.next();
      //   customerArray.push(customerTemp);
      // }
      ctx.logger.info('--------customer1------' + JSON.stringify(customer1));
      ctx.logger.info('--------customer2------' + JSON.stringify(customer2));
      // ctx.logger.info('--------count------' + customerArray.length);
      ctx.setSuccess();
    } catch (err) {
      ctx.logger.error(err);
    }
    ctx.sendResult();
  }
}
